
import { defineStore } from 'pinia';

import {reactive,computed,toRef}  from "vue";

export let useUserStore = defineStore("user",()=>{
    let loginInfo = reactive({
        token:"",
        userid:"",
    })

    let token = toRef(loginInfo,"token");
    let userid = toRef(loginInfo,"userid");

    let isLogin = computed(()=>{
        return !!loginInfo.token&&!!loginInfo.userid;
    })

    // 登录之后更新
    let UpdateAuthorityState = async (params)=>{
        // 更新store
        for(let key in params){
            let val = params[key];
            loginInfo[key] = val;
        }
        // 存储到localStorege
        localStorage.setItem("loginInfo",JSON.stringify(loginInfo));
    }

    // 退出登录 -> 清除
    let clearAuthorityState = async ()=>{
        // 更新store
        let params = {
            token:"",
            userid:"",
        }

        for(let key in params){
            let val = params[key];
            loginInfo[key] = val;
        }
        // 存储到localStorege
        localStorage.removeItem("loginInfo",JSON.stringify(loginInfo));
    }

    // 每次打开页面 -> 初始化state和数据
    let initAuthorityState = async()=>{
        let str = localStorage.getItem("loginInfo");
        if(str){
            let params = JSON.parse(str);
            for(let key in params){
                let val = params[key];
                loginInfo[key] = val;
            }
        }
    }


    return {
        loginInfo,
        token,
        userid,
        isLogin,
        UpdateAuthorityState,
        clearAuthorityState,
        initAuthorityState,
    }
});
